<?php
class NoteHandler
{
	public static function fixNoteCount($iMission) {
		try {
			$oQuery = DataHandler::query("
				SELECT COUNT(*)
				FROM notes
				WHERE mission_id = ?
			", $iMission);

			list($iCount) = $oQuery->fetch();

			DataHandler::query("
				UPDATE missions
				SET note_count = ?
				WHERE id = ?
			", $iCount, $iMission);

			return true;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function delNote($iNoteID, $iMissionID) {
		try {
			DataHandler::query("
				DELETE FROM notes
				WHERE id = ?
			", $iNoteID);

			NoteHandler::fixNoteCount($iMissionID);

			unset($oGlobal['notes'][$_SESSION['iJobID']][$iNoteID]);

			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getNotes($iJob, $iMissionID) {
		try {
			if (is_array(@$GLOBALS['notes'][$iJob])) {
				$oNotes = array();
				foreach ($GLOBALS['notes'][$iJob] as $oThisNote) {
					if ($oThisNote->iMissionID == $iMissionID) {
						$oNotes[$oThisNote->iID] = $oThisNote;
					}
				}
				return $oNotes;
			}

			$oQuery = DataHandler::query("
				SELECT
					id,
					mission_id,
					body,
					user_id,
					timing,
					use_html
				FROM notes
				WHERE job_id = ?
				ORDER BY timing DESC
			", $iJob);

			$GLOBALS['notes'][$iJob] = array();
			while (list($iID, $iMission, $sBody, $iUser, $iTiming, $bUseHTML) = $oQuery->fetch())
			{
				$GLOBALS['notes'][$iJob][$iID] = new Note($iID, $iMission, $sBody, $iUser, $iTiming, $bUseHTML);
			}

			$oNotes = array();
			foreach ($GLOBALS['notes'][$iJob] as $oThisNote)
			{
				if ($oThisNote->iMissionID == $iMissionID) {
					$oNotes[$oThisNote->iID] = $oThisNote;
				}
			}
			
			return $oNotes;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function changeNote($iNoteID, $iMissionID, $sBody, $bUseHTML)
	{
		try {
			// -1 = Unknown SQL error.
			DataHandler::query("
				UPDATE notes
				SET
					body = ?,
					use_html = ?
				WHERE id = ?
				AND mission_id = ?
			", $sBody, boolize($bUseHTML), $iNoteID, $iMissionID);

			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addNote($iJob, $iMissionID, $sBody, $iUser, $iTiming, $bUseHTML)
	{
		try {
			$oQuery = DataHandler::query("
				INSERT INTO notes (
					job_id,
					mission_id,
					body,
					user_id,
					timing,
					use_html
				) VALUES (
					?,
					?,
					?,
					?,
					?,
					?
				)
			", $iJob, $iMissionID, $sBody, $iUser, $iTiming, boolize($bUseHTML));

			$iNewID = DataHandler::lastInsertId();

			NoteHandler::fixNoteCount($iMissionID);

			return $iNewID;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
}
?>
